import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login'
import Layout from '@/views/layout'
import Chart from '@/views/layout/chart'
import User from '@/views/layout/user'
import Enterprise from '@/views/layout/enterprise'
import Question from '@/views/layout/question'
import Subject from '@/views/layout/subject'

// 按需引入 token.js 中的 getToken 方法
import { getToken } from '../utils/token'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/layout',
    name: 'Layout',
    component: Layout,
    children: [
      // 子路由中的path 前面不要加 /
      // 参考： https://router.vuejs.org/zh/guide/essentials/nested-routes.html 下面的黑体字
      { path: 'chart', component: Chart },
      { path: 'user', component: User },
      { path: 'enterprise', component: Enterprise },
      { path: 'question', component: Question },
      { path: 'subject', component: Subject }
    ]
  }
]

const router = new VueRouter({
  routes
})

/**
 * beforeEach 导航守卫
 *
 * to 去往何处
 * from 从何而来
 * next 控制去不去或者去到哪里，并且必须要要调用，否则就会一直卡在这儿
 *  next() 如果里面不加任何参数，就是正常的跳转到下一个页面
 *  next 如果里面加了参数，就是跳转到指定的页面
 */
// 访问的白名单，可以直接通行
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  // 访问的路径在白名单中
  if (whiteList.includes(to.path)) {
    next()
  } else {
    if (getToken()) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
